package com.xuxueli.applyModules.commont;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xuxueli.applyModules.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;

import java.util.*;

/**
 * 实现Job接口
 *
 */
@Slf4j
public class SchedulerQuartzJob1 implements Job{
    private void before(){
        System.out.println("任务开始执行");
    }

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        before();
        System.out.println("开始："+System.currentTimeMillis());
        // TODO 业务
        JobKey jobKey = arg0.getJobDetail().getKey();
        log.info("定时任务开始: {},{}", jobKey.getGroup(), jobKey.getName());
        long beginTime = System.currentTimeMillis();
        JobDetail jobDetail = arg0.getJobDetail();
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        Long batchSearchId = jobDataMap.getLong("id");
        System.out.println(batchSearchId);
        System.out.println("结束："+System.currentTimeMillis());
        after();
        log.info("耗时: {}", System.currentTimeMillis() - beginTime);
        log.info("定时任务结束: {},{}", jobKey.getGroup(), jobKey.getName());
//        STATE_BLOCKED 4 阻塞
//        STATE_COMPLETE 2 完成
//        STATE_ERROR 3 错误
//        STATE_NONE -1 不存在
//        STATE_NORMAL 0 正常
//        STATE_PAUSED 1 暂停
        try {
            List<JobExecutionContext> currentlyExecutingJobs = arg0.getScheduler().getCurrentlyExecutingJobs();
            for (JobExecutionContext jobExecutionContext:currentlyExecutingJobs){
                String triggerName = jobExecutionContext.getJobDetail().getKey().getName();
                String triggerGroup = jobExecutionContext.getJobDetail().getKey().getGroup();
                System.out.println("测试定时器："+triggerName+triggerGroup);
            }
            List<Map<String, Object>> allJob = getAllJob(arg0.getScheduler());
            System.out.println(JSONObject.toJSONString(allJob, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        Date date = new Date(System.currentTimeMillis());
        System.out.println(DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 获取所有任务列表
     */
    public List<Map<String, Object>> getAllJob(Scheduler scheduler) throws SchedulerException {
        GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
        Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
        List<Map<String, Object>> jobList = new ArrayList<>();
        for (JobKey jobKey : jobKeys) {
            List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
            for (Trigger trigger : triggers) {
                Map<String, Object> job = new HashMap<>();
                job.put("jobName", jobKey.getName());
                job.put("jobGroupName", jobKey.getGroup());
                job.put("trigger", trigger.getKey());
                Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
                job.put("jobStatus", triggerState.name());
                if (trigger instanceof CronTrigger) {
                    CronTrigger cronTrigger = (CronTrigger) trigger;
                    String cronExpression = cronTrigger.getCronExpression();
                    job.put("cronExpression", cronExpression);
                }
                jobList.add(job);
            }
        }
        return jobList;
    }

    private void after(){
        System.out.println("任务开始执行");
    }

}
